package 滑动窗口;

import java.util.HashMap;
import java.util.HashSet;

public class 无重复字符的最长子串2 {
    //https://leetcode.cn/problems/longest-substring-without-repeating-characters/description/
    public int lengthOfLongestSubstring1(String s) {
        int left = 0, right = 0, len = 0;
        /*HashSet<Character> hashSet = new HashSet<>();
        char ch = s.charAt(right);
        while (!hashSet.contains(ch)) {
            hashSet.add(ch);
        }*/
        HashSet<Character> hashSet = new HashSet<>();
        while (right < s.length()) {
            while (right < s.length() && !hashSet.contains(s.charAt(right))) {// 第一次到全部 都一视同仁地 正常录
                char ch = s.charAt(right);
                hashSet.add(ch);
                right++;
            }
            len = Math.max(len,right - left);
            while (left < s.length() && right < s.length() && s.charAt(left) != s.charAt(right)) {
                hashSet.remove(s.charAt(left++));
            }
            hashSet.remove(s.charAt(left++));
        }
        return len;
    }

    public int lengthOfLongestSubstring(String ss) {
        char[] s = ss.toCharArray(); // 不用在字符串那边s.CharAt(right)来获取字符了，直接数组索引s[right]
        int [] hash = new int[128]; // 用数组模拟哈希表
        int left = 0, right = 0, n = ss.length(), ret = 0;
        while(right < n) {
            hash[s[right]]++; // 进入窗口 - 判断(出) - 出窗口
            while(hash[s[right]] > 1) { // 判断(出)
                hash[s[left++]]--; // 出窗口
            }
            ret = Math.max(ret,right - left + 1);
            right++;
        }
        return ret;
    }
}
